<template>
  <div class="my-consultations">
    <div class="header">
      <h2>{{ authStore.userType === 'teacher' ? '教师' : '学生' }}咨询管理</h2>
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane :label="`我的${authStore.userType === 'teacher' ? '解答' : '提问'}`" name="questions"></el-tab-pane>
        <el-tab-pane label="我的回答" name="answers"></el-tab-pane>
      </el-tabs>
    </div>

    <!-- 统一的问题/解答列表 -->
    <div v-if="activeTab === 'questions'" class="qa-list">
      <el-card v-for="item in myQuestions" :key="item.id" class="qa-card">
        <div class="qa-header">
          <h3>{{ item.content }}</h3>
          <div class="meta">
            <span>{{ formatDate(item.createTime) }}</span>
            <span>{{ item.questionType || '无分类' }}</span>
            <el-tag v-if="authStore.userType === 'teacher'" type="info">教师解答</el-tag>
          </div>
        </div>
        <div class="qa-footer">
          <span>回答数: {{ item.commentCount || 0 }}</span>
          <el-button type="text" @click="viewDetail(item.id)">查看详情</el-button>
        </div>
      </el-card>
      <el-empty v-if="myQuestions.length === 0" :description="`暂无${authStore.userType === 'teacher' ? '解答' : '提问'}`"></el-empty>
    </div>

    <!-- 统一的回答列表 -->
    <div v-else class="qa-list">
      <el-card v-for="item in myAnswers" :key="item.id" class="qa-card">
        <div class="qa-header">
          <h3>{{ item.content }}</h3>
          <div class="meta">
            <span>{{ formatDate(item.createTime) }}</span>
            <el-tag v-if="item.isAdopted" type="success">已采纳</el-tag>
            <el-tag :type="item.isStudent ? '' : 'info'">
              {{ item.isStudent ? '学生回答' : '教师回答' }}
            </el-tag>
            <el-button type="danger" size="small" @click="deleteItem(item.id, 'answer')">删除</el-button>
          </div>
        </div>
      </el-card>
      <el-empty v-if="myAnswers.length === 0" description="暂无回答"></el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()

const activeTab = ref('questions')
const myQuestions = ref([])
const myAnswers = ref([])

// 统一获取用户信息
const fetchUserInfo = async () => {
  try {
    console.log('当前用户信息:', {
      userId: authStore.userId,
      userType: authStore.userType
    })
    
    if (!authStore.userType) {
      throw new Error('无法获取用户类型')
    }
    
    return {
      id: authStore.userId,
      isTeacher: authStore.userType === 'teacher'
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
    return null
  }
}

// 统一加载数据
// 修改loadData方法
const loadData = async () => {
  const userInfo = await fetchUserInfo()
  if (!userInfo) return
  
  try {
    console.log('开始加载数据，用户ID:', userInfo.id)
    
    // 打印请求URL
    // 使用新的接口
    const questionsUrl = `/api/questions/user/${userInfo.id}`;
    const answersUrl = `/api/questions/comments?userId=${userInfo.id}`
    console.log('问题请求URL:', questionsUrl)
    console.log('回答请求URL:', answersUrl)
    
    const [questionsRes, answersRes] = await Promise.all([
      axios.get(questionsUrl),
      axios.get(answersUrl)
    ])
    
    console.log('问题API响应:', questionsRes)
    console.log('回答API响应:', answersRes)
    
    myQuestions.value = questionsRes.data
    myAnswers.value = answersRes.data
    
    console.log('加载完成，问题数量:', myQuestions.value.length)
    console.log('加载完成，回答数量:', myAnswers.value.length)
  } catch (error) {
    console.error('加载数据错误:', error)
    ElMessage.error('加载数据失败: ' + error.message)
  }
}

// 统一删除操作
const deleteItem = async (id, type) => {
  try {
    const userInfo = await fetchUserInfo()
    if (!userInfo) return
    
    const endpoint = type === 'question' 
      ? `/api/questions/questions?userId=${userInfo.id}&questionId=${id}`
      : `/api/questions/comments?userId=${userInfo.id}&commentId=${id}`
    
    await axios.delete(endpoint)
    
    if (type === 'question') {
      myQuestions.value = myQuestions.value.filter(q => q.id !== id)
    } else {
      myAnswers.value = myAnswers.value.filter(a => a.id !== id)
    }
    
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error('删除失败: ' + error.message)
  }
}

// 查看问题详情
const viewDetail = (questionId) => {
  router.push({ name: 'question-detail', params: { id: questionId } })
}

// 查看问题 (与viewDetail相同)
const viewQuestion = (questionId) => {
  router.push({ name: 'question-detail', params: { id: questionId } })
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  try {
    return new Date(dateString).toLocaleString()
  } catch {
    return dateString
  }
}

// 切换标签页
const handleTabChange = () => {
  // 不需要额外处理，因为数据已经预加载
}

// 初始化加载
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.my-consultations {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  margin-bottom: 30px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.qa-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.qa-card {
  transition: all 0.3s;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.qa-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.qa-header {
  margin-bottom: 10px;
  flex-grow: 1;
}

.qa-header h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.meta {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
  font-size: 14px;
  color: #666;
}

.qa-footer {
  display: flex;
  align-items: center;
  gap: 15px;
  font-size: 14px;
  color: #666;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.el-tag {
  margin-left: 5px;
}
</style>